package com.my.test.netty.test;

import com.my.test.netty.NettyClient;
import com.my.test.netty.NettyClientHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class Client {

	private String host;
	private int port;
	public Client(){
		
	}
	public Client(String host,int port){
		this.host = host;
		this.port = port;
	}
	public Bootstrap getBoot(){
		EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.group(eventLoopGroup);
		bootstrap.remoteAddress(this.host, this.port);
		return bootstrap;
	}
	public Bootstrap getBoot(String host,int port){
		EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
		Bootstrap bootstrap = new Bootstrap();
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.group(eventLoopGroup);
		bootstrap.remoteAddress(host, port);
		return bootstrap;
	}
	public void sendMsg(Bootstrap bootstrap,final String msg) throws InterruptedException {
		try {
			bootstrap.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel socketChannel)
						throws Exception {					
					socketChannel.pipeline().addLast(new ChannelHandlerAdapter(){
						@Override
						public void channelActive(ChannelHandlerContext ctx) throws Exception {
							ByteBuf ff = Unpooled.buffer();
							ff.writeBytes(msg.getBytes());
							ctx.writeAndFlush(ff);
						}
					});
				}
			});
			ChannelFuture future = bootstrap.connect(host, port).sync();
			future.channel().closeFuture().sync();
		} finally {
		}
	}

	public static void main(String[] args) throws InterruptedException {
		for(int i=0;i<10;i++){
			new Thread(new Runnable() {
				@Override
				public void run() {
					Client c = new Client("127.0.0.1", 9999);
					try {
						c.sendMsg(c.getBoot(),"hello world hzb!");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}
}
